using UnityEngine;
using System;
using System.Collections;
using System.Text;
using System.Net;
using System.Net.Sockets;



public class CsdSocket_TCP {
    public Socket s = null;
    public byte[] bytesReceived = new byte[1024*2];
    public byte[] bytesReceivedTemp = new byte[1024 + 6];
    public int recvedBufCount = 0;
    public byte[] bytesSend = new byte[1024+256];
    public bool isclose = false;
    public void Attach(Socket _s)    {
        s = _s;
    }
    virtual public int HandleID()
    {
        return (int)s.Handle;
    }
    virtual public bool IsConnectionReady()
    {
        if (s != null)
        {
            return s.Connected;
        }
        return false;
    }
    virtual public int Send_buf(byte[] sendbuf, int length)
    {
        try
        {
            if (IsConnectionReady())
            {
                //byte[] bytesSent = Encoding.ASCII.GetBytes(sendbuf);
                int sentsize = s.Send(sendbuf, length, 0);
                return sentsize;
            }
        }
        catch (System.Exception)
        {

        }
        return -1;
    }
    virtual public int Recv_buf()
    {
        int bytes = s.Receive(bytesReceivedTemp, bytesReceivedTemp.Length, 0);
        return bytes;
    }
    public void SendProtocol_Real(PROTOCOLDEFINE p, ushort msgID)
    {
        try
        {
            int capacity = 0;
            byte[] buf = p.GetSendbuf(ref capacity);
            if (buf != null)
            {
                SendProtocol(msgID, buf, (ushort)capacity);
            }
        }
        catch (System.Exception)
        {
        	
        }
    }

    public void SendProtocol(ushort msgID, byte[] sendbuf, ushort length)
    {
        try
        {
            if (IsConnectionReady())
            {
                if (length > 1024 || length > sendbuf.Length)
                {
                    UnityEngine.Debug.Log("send size error ,msgid :" + msgID + " packetsize:" + length);
                    return;
                }
                if (sendbuf == null)
                {
                    UnityEngine.Debug.Log("send size error ,sendbuf null :");
                    return;
                }
                int headsize = 0;
                CSHARP_MSGHEADER head = new CSHARP_MSGHEADER();
                head.msgID = msgID;
                head.msgLength = length;
                byte [] headbuf = head.GetSendbuf(ref headsize);
                Array.Copy(headbuf, 0, bytesSend, 0, headsize);
                Array.Copy(sendbuf, 0, bytesSend, headsize, length);

                //int sentsize = s.Send(bytesSend, headsize + length, 0);
                int sentsize = Send_buf(bytesSend, headsize + length);
                UnityEngine.Debug.Log("client sentsize is :" + sentsize);
            }
            else
            {
                UnityEngine.Debug.Log("not connected");
            }
        }
        catch (System.Exception ex)
        {
            UnityEngine.Debug.Log("sendprotocol failed "+msgID + " execption: "+ex.Message);
        }
    }

    public byte[] RecvAndReturn(ref int count)
    {
        try
        {
            if (IsConnectionReady())
            {
                //int bytes = s.Receive(bytesReceivedTemp, bytesReceivedTemp.Length, 0);
                int bytes = Recv_buf();
                Array.Copy(bytesReceivedTemp, 0, bytesReceived, recvedBufCount, bytes);
                recvedBufCount += bytes;
                count = recvedBufCount;
                return bytesReceived;
            }
        }
        catch (SocketException e)
        {
            if (e.ErrorCode != 10035 )
            {
                UnityEngine.Debug.Log("errr " + e.ErrorCode);
                s.Shutdown(SocketShutdown.Both);
                s.Close();
                isclose = true;
            }
        }
        return null;
    }

    public void SetRecvIndex(int movetoHeadSize)
    {
        if (movetoHeadSize >= recvedBufCount)
        {
            recvedBufCount = 0;
        }
        else
        {
            Array.Copy(bytesReceived, movetoHeadSize, bytesReceivedTemp, 0, recvedBufCount - movetoHeadSize);
            recvedBufCount = recvedBufCount - movetoHeadSize;
            Array.Copy(bytesReceivedTemp, 0, bytesReceived, 0, recvedBufCount);
        }
    }
}
